<template>
  <div class="">
    <el-card>
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addTrademark"
      >
        添加品牌
      </el-button>
      <el-table style="margin: 10px 0px" border :data="dataList">
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <!-- table-column:默认展示数据用div -->
        <el-table-column label="品牌名称" prop="tmName"> </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="editTrademark(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除${row.tmName}?`"
              width="250px"
              icon="Delete"
              @confirm="removeTradeMark(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件
                pagination
                   v-model:current-page:设置分页器当前页码
                   v-model:page-size:设置每一个展示数据条数
                   page-sizes:用于设置下拉菜单数据
                   background:设置分页器按钮的背景颜色
                   layout:可以设置分页器六个子组件布局调整
            -->
      <el-pagination
        @current-change="getHasTrademark"
        @size-change="sizeChange"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 10]"
        :size="size"
        :background="background"
        layout=" prev, pager, next, jumper,->,total, sizes"
        :total="total"
      />
    </el-card>
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
      width="800"
    >
      <el-form
        style="width: 85%"
        :model="trademarkParams"
        ref="formRef"
        :rules="rules"
      >
        <el-form-item label="品牌名称" label-width="80px" prop="tmName">
          <el-input
            v-model="trademarkParams.tmName"
            placeholder="请输入商品名称"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            action="/api/admin/product/fileUpload"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts"  setup>
import { ElMessage, UploadProps, formEmits } from "element-plus";
import {
  trademarkList,
  reqAddOrUpdateTrademark,
  removeTrademark,
} from "@/api/product/trademark/index.ts";
import { ref, onMounted, reactive, nextTick } from "vue";
import {} from "vue-router";
import type {
  TradeMarkResponseData,
  Records,
  TradeMark,
} from "@/api/product/trademark/type.ts";
//当前页码
let pageNo = ref<number>(1);
//每一页展示多少条数据
let limit = ref<number>(3);
const size = ref<ComponentSize>("default");
const background = ref(false);
let dataList = ref<Records>([]);
let total = ref<Number>(0);
let dialogFormVisible = ref<Boolean>(false);
let dialogoTitle = ref<String>("");
// 获取form组件的实例
let formRef = ref();
let trademarkParams = reactive<TradeMark>({
  tmName: "",
  logoUrl: "",
});
const getHasTrademark = async (pager = 1) => {
  console.log("我看看这个页面是啥意思", pager);

  pageNo.value = pager;
  let result: TradeMarkResponseData = await trademarkList(
    pageNo.value,
    limit.value
  );
  if (result.code == 200) {
    // console.log(result.data, "品牌数据");
    total.value = result.data.total;
    dataList.value = result.data.records;
  }
};
onMounted(() => {
  getHasTrademark();
});
// const getHasTrademark = () => {
//   markList();
// };

// 当下拉菜单发生变化的时候触达的方法
const sizeChange = () => {
  // pageNo.value = 1;
  getHasTrademark();
};
// 上传照片的操作
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  console.log(response, uploadFile, "图片上传成功的参数");
  trademarkParams.logoUrl = response.data;
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate("logoUrl");
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
  //要求:上传文件格式png|jpg|gif 4M
  if (
    rawFile.type == "image/png" ||
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传文件大小小于4M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传文件格式务必PNG|JPG|GIF",
    });
    return false;
  }
};
// 添加商品的操作
const addTrademark = () => {
  dialogFormVisible.value = true;
  dialogoTitle.value = "添加";
  //清空收集数据
  // 这个设置为零 在三元表达式中 判断会判断为false
  trademarkParams.id = 0;
  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";
  nextTick(() => {
    formRef.value.clearValidate("tmName");
    formRef.value.clearValidate("logoUrl");
  });
};
// 对话框底部确认按钮
const confirm = async () => {
  //在你发请求之前,要对于整个表单进行校验
  //调用这个方法进行全部表单相校验,如果校验全部通过，在执行后面的语法
  await formRef.value.validate();
  let result = await reqAddOrUpdateTrademark(trademarkParams);
  //添加|修改已有品牌
  if (result.code == 200) {
    //关闭对话框
    dialogFormVisible.value = false;
    //弹出提示信息
    ElMessage({
      type: "success",
      message: trademarkParams.id ? "修改品牌成功" : "添加品牌成功",
    });
    //再次发请求获取已有全部的品牌数据

    getHasTrademark(trademarkParams.id ? pageNo.value : 1);
  } else {
    //添加品牌失败
    ElMessage({
      type: "error",
      message: "添加品牌失败",
    });
    //关闭对话框
    dialogFormVisible.value = false;
  }
};
//对话框底部取消按钮
const cancel = () => {
  //对话框隐藏
  dialogFormVisible.value = false;
};
// 修改商品的操作
const editTrademark = (row) => {
  nextTick(() => {
    formRef.value.clearValidate("tmName");
    formRef.value.clearValidate("logoUrl");
  });
  dialogFormVisible.value = true;
  dialogoTitle.value = "修改";
  console.log(row, "每一行的数据");
  Object.assign(trademarkParams, row);
};
//品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  //是当表单元素触发blur时候,会触发此方法
  //自定义校验规则
  if (value.trim().length >= 2) {
    callBack();
  } else {
    //校验未通过返回的错误的提示信息
    callBack(new Error("品牌名称位数大于等于两位"));
  }
};
//品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  //如果图片上传
  if (value) {
    callBack();
  } else {
    callBack(new Error("LOGO图片务必上传"));
  }
};
// 商品组件的表单验证
const rules = {
  tmName: [{ require: true, trigger: "blur", validator: validatorTmName }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
};
// 删除商品的操作
const removeTradeMark = async (id: Number) => {
  let result = removeTrademark(id);
  if (result.code == 200) {
    //删除成功提示信息
    ElMessage({
      type: "success",
      message: "删除品牌成功",
    });
    //再次获取已有的品牌数据
    getHasTrademark(
      dataList.value.length > 1 ? pageNo.value : pageNo.value - 1
    );
  } else {
    ElMessage({
      type: "error",
      message: "删除品牌失败",
    });
  }
};
</script>

<style  scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>